package com.maruping.disk.spring.config;

import com.alibaba.fastjson.JSON;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component

public class LogAdviceConfig {
    private static Logger logger = LogManager.getLogger("DiskApplication");
    @Pointcut("execution(* com.maruping..control.*.*(..))")
    public void controlPointcut(){

    }
    @Before("controlPointcut()")
    public void printControlLog(JoinPoint joinPoint){
        logger.info(dealLog(joinPoint));
    }

    private String dealLog(JoinPoint joinPoint){
        StringBuffer sb = new StringBuffer();
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        String[] paramNames = signature.getParameterNames();
        Object[] args = joinPoint.getArgs();
        for(int i = 0 ; i < paramNames.length; i++){
            sb.append(paramNames[i]);
            sb.append("=");
            sb.append(args[i]);
            sb.append(";");
        }

        String rstStr = sb.toString();
        if(rstStr.length() > 0){
            rstStr = rstStr.substring(0,rstStr.length() - 1);
        }

        return  joinPoint.getSignature().getDeclaringTypeName()
                + "\n"
                + joinPoint.getSignature().getName()
                + "("
                + rstStr
                + ")";
    }

    @Around("@annotation(com.maruping.disk.spring.annotation.LogPoint)")
    public Object printServiceLog(ProceedingJoinPoint joinPoint) throws Throwable {

        dealLog(joinPoint);
        logger.info(dealLog(joinPoint));
        Object rst = joinPoint.proceed();


        logger.info(joinPoint.getSignature().getDeclaringTypeName()
                + "\n"
                + joinPoint.getSignature().getName()
                + " "
                + JSON.toJSONString(rst)
        );

        return rst;

    }

}